package com.zzzzzz.content.article;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.common.GlobalConstants;
import com.zzzzzz.content.tag.TagService;
import com.zzzzzz.core.exception.NoSuchModelException;

@Service("articleService")
public class ArticleServiceImpl implements ArticleService{

	@Resource
	private ArticleDao articleDao;
	@Resource
	private TagService tagService;
	
	@Transactional
	public Long add(Long userId, ArticleForm articleForm) {
		Article article = new Article();
		articleForm.updateArticle(article);
		article.setUserId(userId);
		article.setLooks(0);
		article.setLikes(0);
		article.setReplies(0);
		article.setStatus(0);
		articleDao.add(article);
		
		Long id = article.getId();
		tagService.updateTagByAddTopic(id, articleForm.getTags());
		
		return id;
	}
	
	@Transactional
	public void del(Long id, Long userId) throws NoSuchModelException {
		Article article = articleDao.findById(id);
		articleDao.editStatus(id, GlobalConstants.STATUS.DELETED, userId);
		tagService.updateTagByDelTopic(id, article.getTags());
	}
	
	@Transactional
	public void edit(Long userId, Long id, ArticleForm articleForm) {
		Article article = new Article();
		article.setId(id);
		articleForm.updateArticle(article);
		article.setUserId(userId);
		
		articleDao.edit(article);
		tagService.updateTagByEditTopic(id, articleForm.getTags());
	}

	public Article findById(Long id) {
		return articleDao.findById(id);
	}
	
	public ArticleView findViewById(Long id) {
		return articleDao.findViewById(id);
	}
	
	public void plusLooks(Long id) {
		articleDao.editLooks(id, 1);
	}

	public void plusReplies(Long id, Long userId) {
		articleDao.editReplies(id, 1);
	}
	
	public void editLikes(Long id, Integer likesPlus) {
		articleDao.editLikes(id, likesPlus);
	}

}
